/**
 * 通知模板页
 */
import React from 'react';
import { Button, Anchor, Popconfirm, Table, Drawer, message, Spin, Form, Tag } from 'antd';
import { history } from 'umi'
import { useRequest, defaultFormatResult } from '@/hooks';
import authHelper from '@/utils/auth/helper';
import { DividerContainer } from '@/molecules';
import { getTabContainer } from '@/utils/utils';

import { FormHeader, Icon, AntIcon } from '../components';
import { PeriodItem } from './containers';
import EmailCompanyConfigs from './containers/EmailCompanyConfigs';
import NoticeDetail from './NoticeDetail';
import {
    getNoticeTemplateList,
    deleteNoticeTemplate,
    getRecruitParam,
    updateRecruitParam,
    getRecruitEmailCompanyList,
    getRecruitEmailCompanyById,
    delRecruitEmailCompany
} from './service';
import { TEMPLATE_TYPE, TEMPLATE_TITLE, RECRUIT_CODE } from './constants';

const { checkCode } = authHelper;
const { Link } = Anchor;

const AddButton = ({ type, onClick }) => (
    <Button type="dashed" icon="plus" block style={{ marginTop: 12 }} onClick={() => onClick(type)}>
        添加
    </Button>
);

const NoticeTemplate = () => {
    const [visible, setVisible] = React.useState(false);
    const [params, setParams] = React.useState(null);
    const [periodType, setPeriodType] = React.useState('');
    const [companyQuery, setCompanyQuery] = React.useState({});
    const [emailVisible, setEmailVisible] = React.useState(false);
    const [emailInfo, setEmailInfo] = React.useState({});
    const [defaultOrg, setDefaultOrg] = React.useState(false);
    const [disabledList, setDisabledList] = React.useState([]);
    const [usedEmail, setUsedEmail] = React.useState([]);
    // 查询机构邮箱列表
    const { data: recruitEmailData = [], loading: recruitEmailLoading, run: fetchRecruitEmailCompanyList } = useRequest(
        query => getRecruitEmailCompanyList(query),
        {
            manual: true,
            formatResult: result => {
                const { code, data, msg } = result;
                if (code === 10000) {
                    const usedCompanyCode = [];
                    const usedEmailList = [];
                    data.map(item => {
                        usedCompanyCode.push(item.companyCode);
                        usedEmailList.push(item.email);
                        return usedCompanyCode;
                    });
                    setDisabledList(usedCompanyCode);
                    setUsedEmail(usedEmailList);
                    return data;
                }
                message.error(msg);
                return [];
            }
        }
    );
    // 获取模板列表
    const { data: templateData, loading: templateLoading, run: fetchTemplateList } = useRequest(
        () => getNoticeTemplateList({ templateCategory: 1, pageSize: 99999 }),
        {
            manual: true,
            initialData: { interviewList: [], offerList: [], eliminateList: [], backgroundList: [] },
            formatResult: result => {
                const { code, data, msg } = result;
                if (code === 10000) {
                    const { rows = [] } = data;
                    return {
                        interviewList: rows.filter(item => item.templateType === TEMPLATE_TYPE.INTERVIEW),
                        offerList: rows.filter(item => item.templateType === TEMPLATE_TYPE.OFFER),
                        eliminateList: rows.filter(item => item.templateType === TEMPLATE_TYPE.ELIMINATE),
                        backgroundList: rows.filter(item => item.templateType === TEMPLATE_TYPE.BACKGROUND)
                    };
                }
                message.error(msg);
                return { interviewList: [], offerList: [], eliminateList: [], backgroundList: [] };
            }
        }
    );

    // 删除模板
    const { run: delNoticeTemplate } = useRequest(deleteNoticeTemplate, {
        manual: true,
        onSuccess: res => {
            const { code, msg } = res;
            if (code === 10000) {
                fetchTemplateList();
                message.success('操作成功');
                return;
            }
            message.error(msg);
        }
    });

    // 获取面试反馈链接有效期
    const { data: interviewPeriod, loading: interviewPeriodLoading, run: fetchInterviewPeriod } = useRequest(
        () => getRecruitParam(RECRUIT_CODE.INTERVIEW_EFFECTIVE),
        {
            manual: true,
            ...defaultFormatResult
        }
    );

    // 获取录用反馈链接有效期
    const { data: offerPeriod, loading: offerPeriodLoading, run: fetchOfferPeriod } = useRequest(
        () => getRecruitParam(RECRUIT_CODE.OFFER_EFFECTIVE),
        {
            manual: true,
            ...defaultFormatResult
        }
    );

    // 更新链接有效期
    const { run: updateParam, loading: paramLoading } = useRequest(updateRecruitParam, {
        manual: true,
        onSuccess: res => {
            const { code, msg } = res;
            if (code === 10000) {
                if (periodType === RECRUIT_CODE.INTERVIEW_EFFECTIVE) {
                    fetchInterviewPeriod();
                } else {
                    fetchOfferPeriod();
                }
                message.success('操作成功');
                return;
            }
            message.error(msg);
        }
    });

    const handleAdd = type => {
        history.push({
            pathname: '/office/personnelManagement/recruitment/setting/notice/add',
            query: { type }
        });
    };

    const handleDelete = id => {
        if (id) {
            delNoticeTemplate(id);
        }
    };

    const handleSave = (type, value) => {
        setPeriodType(type);
        updateParam({
            id: type === RECRUIT_CODE.INTERVIEW_EFFECTIVE ? interviewPeriod?.id : offerPeriod?.id,
            paramCode: type,
            paramValue: value
        });
    };

    React.useEffect(() => {
        fetchTemplateList();
        fetchInterviewPeriod();
        fetchOfferPeriod();
    }, []);
    React.useEffect(() => {
        fetchRecruitEmailCompanyList(companyQuery);
    }, [companyQuery]);
    const columns = [
        {
            title: '序号',
            dataIndex: 'id',
            width: 80,
            render: (text, record, index) => index + 1
        },
        {
            title: '模板名称',
            dataIndex: 'templateName',
            ellipsis: true
        },
        {
            title: '邮件标题',
            dataIndex: 'templateTitle',
            ellipsis: true
        },
        {
            title: '操作',
            dataIndex: 'operation',
            width: 130,
            render: (text, record) => (
                <DividerContainer>
                    <AntIcon
                        title="查看"
                        type="eye"
                        onClick={() => {
                            setParams({
                                type: record.templateType,
                                id: record.id
                            });
                            setVisible(true);
                        }}
                        style={{ marginBottom: 6 }}
                    />
                    {checkCode('office:recruitment:setting:notice:update') && (
                        <Icon
                            title="编辑"
                            type="listfunction_edit_icon_default"
                            onClick={() => {
                                history.push({
                                    pathname: '/office/personnelManagement/recruitment/setting/notice/edit',
                                    query: { id: record.id, type: record.templateType }
                                });
                            }}
                        />
                    )}
                    {checkCode('office:recruitment:setting:notice:delete') && record.isDefault === 0 && (
                        <Popconfirm
                            title="确定删除该模板吗？"
                            okText="确定"
                            cancelText="取消"
                            onConfirm={() => handleDelete(record.id)}
                        >
                            <Icon title="删除" type="listfunction_delete_icon_default" onClick={() => {}} />
                        </Popconfirm>
                    )}
                </DividerContainer>
            )
        }
    ];
    // 录用、背调专用
    const getColumns = () => {
        const arr = [...columns];
        arr.splice(3, 0, {
            title: '适用行政机构',
            dataIndex: 'organizationNames',
            ellipsis: true,
            width: '40%',
            render: text => text.replace(/,/g, '、')
        });
        // 加入 默认tag显示，isDefault = 1
        arr[1] = {
            title: '模板名称',
            dataIndex: 'templateName',
            ellipsis: true,
            render: (text, record) => {
                let val = text;
                if (record.isDefault === 1 && text !== '') {
                    val = (
                        <span>
                            {text}{' '}
                            <Tag color="orange" style={{ marginLeft: 8 }}>
                                默认
                            </Tag>
                        </span>
                    );
                }
                return val;
            }
        };
        //
        return arr;
    };

    // 确定
    const handleOk = () => {
        setEmailVisible(false);
        setEmailInfo({});
        setDefaultOrg(false);
        fetchRecruitEmailCompanyList(companyQuery);
    };
    // 取消
    const handleCancel = () => {
        setEmailInfo({});
        setDefaultOrg(false);
        setEmailVisible(false);
    };
    // 查询邮箱
    const { run: fetchEmailById } = useRequest(id => getRecruitEmailCompanyById(id), {
        manual: true,
        formatResult: result => {
            const { code, data, msg } = result;
            if (code === 10000) {
                setEmailInfo(data);
            } else {
                setEmailVisible(false);
                fetchRecruitEmailCompanyList(companyQuery);
                message.error(msg);
            }
        }
    });
    // 删除邮箱
    const { run: delEmailById } = useRequest(id => delRecruitEmailCompany(id), {
        manual: true,
        formatResult: result => {
            const { code, msg } = result;
            if (code === 10000) {
                fetchRecruitEmailCompanyList(companyQuery);
                return message.success('成功删除邮箱');
            }
            message.error(msg);
            setEmailVisible(false);
            fetchRecruitEmailCompanyList();
            return [];
        }
    });
    // 新增邮箱
    const handleAddEmail = (id, org) => {
        if (id) {
            fetchEmailById(id);
        }
        if (org === 1 && org) {
            setDefaultOrg(true);
        }
        setEmailVisible(true);
    };
    // 删除邮箱
    const handleDelEmail = id => {
        delEmailById(id);
    };

    const ORDER_MAP = { ascend: 'asc', descend: 'desc' };
    const handleTableChange = (_, __, sorter) => {
        setCompanyQuery({
            ...companyQuery,
            updateTimeOrderBy: ORDER_MAP[sorter.order]
        });
    };
    const emailColumns = [
        {
            title: '序号',
            dataIndex: 'id',
            width: 80,
            render: (text, record, index) => index + 1
        },
        {
            title: '邮箱',
            dataIndex: 'email',
            ellipsis: true,
            render: (text, record) => {
                let val = '';
                if (record.defaultFlag === 1 && text !== '') {
                    val = (
                        <span>
                            {text}{' '}
                            <Tag color="orange" style={{ marginLeft: 8 }}>
                                默认
                            </Tag>
                        </span>
                    );
                }
                if (record.defaultFlag === 1 && text === '') {
                    val = (
                        <span>
                            --{' '}
                            <Tag color="orange" style={{ marginLeft: 8 }}>
                                默认
                            </Tag>
                        </span>
                    );
                }
                if (record.defaultFlag === 0 && text !== '') {
                    val = text;
                }
                if (record.defaultFlag === 0 && text === '') {
                    val = '--';
                }
                return val;
            }
        },
        {
            title: '适用行政机构',
            dataIndex: 'companyName',
            ellipsis: true,
            render: (text, record) => (record.defaultFlag === 1 ? '全集团' : text)
        },
        {
            title: '编辑时间',
            dataIndex: 'updateTime',
            ellipsis: true,
            sorter: () => {}
        },
        {
            title: '操作',
            dataIndex: 'operation',
            width: 130,
            render: (text, record) => (
                <DividerContainer>
                    {checkCode('office:recruitment:setting:notice:update') && (
                        <Icon
                            title="编辑"
                            type="listfunction_edit_icon_default"
                            onClick={() => handleAddEmail(record.id, record.defaultFlag)}
                        />
                    )}
                    {checkCode('office:recruitment:setting:notice:delete') && record.defaultFlag === 0 && (
                        <Popconfirm
                            title="你确定要删除这行内容吗？"
                            okText="确定"
                            cancelText="取消"
                            onConfirm={() => handleDelEmail(record.id)}
                        >
                            <Icon title="删除" type="listfunction_delete_icon_default" onClick={() => {}} />
                        </Popconfirm>
                    )}
                </DividerContainer>
            )
        }
    ];
    const titleStyle = { color: 'rgba(0, 0, 0, 0.3)' };
    return (
        <div style={{ display: 'flex', justifyContent: 'space-between' }}>
            <div style={{ maxWidth: 1000 }}>
                <div style={{ marginBottom: 24, position: 'relative' }}>
                    <FormHeader title="通知发件邮箱" id="interview0" style={{ marginBottom: 8 }} />
                    <div style={{ ...titleStyle, marginBottom: 12 }}>设置候选人应聘通知的发件邮箱</div>
                    <Spin spinning={recruitEmailLoading}>
                        <Table
                            rowKey="id"
                            columns={emailColumns}
                            dataSource={recruitEmailData || []}
                            pagination={false}
                            onChange={handleTableChange}
                        />
                        {checkCode('office:recruitment:setting:notice:create') && (
                            <AddButton onClick={handleAddEmail} />
                        )}
                    </Spin>
                </div>
                <div style={{ marginBottom: 24 }}>
                    <FormHeader title="面试通知" id="interview1" style={{ marginBottom: 8 }} />
                    <div style={titleStyle}>发送给候选人的面试邀请。</div>
                    <PeriodItem
                        beforeStr="面试反馈链接有效期"
                        afterStr="小时"
                        value={interviewPeriod?.paramValue || ''}
                        loading={
                            interviewPeriodLoading || (paramLoading && periodType === RECRUIT_CODE.INTERVIEW_EFFECTIVE)
                        }
                        onSave={v => handleSave(RECRUIT_CODE.INTERVIEW_EFFECTIVE, v)}
                        disabled={!checkCode('office:recruitment:setting:notice:period')}
                    />
                    <Spin spinning={templateLoading}>
                        <Table
                            rowKey="id"
                            columns={columns}
                            dataSource={templateData?.interviewList}
                            pagination={false}
                        />
                        {checkCode('office:recruitment:setting:notice:create') && (
                            <AddButton type={TEMPLATE_TYPE.INTERVIEW} onClick={handleAdd} />
                        )}
                    </Spin>
                </div>

                <div style={{ marginBottom: 24 }}>
                    <FormHeader title="录用通知" id="interview2" style={{ marginBottom: 8 }} />
                    <div style={titleStyle}>发送给候选人的offer，一个行政机构必须且只能关联一个模板。</div>
                    <PeriodItem
                        beforeStr="录用反馈链接有效期"
                        afterStr="小时"
                        value={offerPeriod?.paramValue || ''}
                        loading={offerPeriodLoading || (paramLoading && periodType === RECRUIT_CODE.OFFER_EFFECTIVE)}
                        onSave={v => handleSave(RECRUIT_CODE.OFFER_EFFECTIVE, v)}
                        disabled={!checkCode('office:recruitment:setting:notice:period')}
                    />
                    <Spin spinning={templateLoading}>
                        <Table
                            rowKey="id"
                            columns={getColumns()}
                            dataSource={templateData?.offerList}
                            loading={templateLoading}
                            pagination={false}
                        />
                        {checkCode('office:recruitment:setting:notice:create') && (
                            <AddButton type={TEMPLATE_TYPE.OFFER} onClick={handleAdd} />
                        )}
                    </Spin>
                </div>

                <div style={{ marginBottom: 24 }}>
                    <FormHeader title="背调通知" id="interview3" style={{ marginBottom: 8 }} />
                    <div style={{ ...titleStyle, marginBottom: 12 }}>用于发送给第三方背调机构收集背调反馈。</div>
                    <Spin spinning={templateLoading}>
                        <Table
                            rowKey="id"
                            columns={getColumns()}
                            dataSource={templateData?.backgroundList}
                            loading={templateLoading}
                            pagination={false}
                        />
                        {checkCode('office:recruitment:setting:notice:create') && (
                            <AddButton type={TEMPLATE_TYPE.BACKGROUND} onClick={handleAdd} />
                        )}
                    </Spin>
                </div>

                <div style={{ marginBottom: 24 }}>
                    <FormHeader title="淘汰通知" id="interview4" style={{ marginBottom: 8 }} />
                    <div style={{ ...titleStyle, marginBottom: 12 }}>确定淘汰后发送给应聘者的通知。</div>
                    <Spin spinning={templateLoading}>
                        <Table
                            rowKey="id"
                            columns={columns}
                            dataSource={templateData?.eliminateList}
                            loading={templateLoading}
                            pagination={false}
                        />
                        {checkCode('office:recruitment:setting:notice:create') && (
                            <AddButton type={TEMPLATE_TYPE.ELIMINATE} onClick={handleAdd} />
                        )}
                    </Spin>
                </div>
            </div>
            <Anchor getContainer={() => getTabContainer()} offsetTop={24} style={{ padding: '0 30px' }}>
                <Link href="#interview0" title="通知发件邮箱" />
                <Link href="#interview1" title="面试通知" />
                <Link href="#interview2" title="录用通知" />
                <Link href="#interview3" title="背调通知" />
                <Link href="#interview4" title="淘汰通知" />
            </Anchor>
            <Drawer
                title={TEMPLATE_TITLE[params?.type] || '通知模板'}
                placement="right"
                // maskStyle={{ background: 'transparent' }}
                width={600}
                onClose={() => setVisible(false)}
                visible={visible}
            >
                <NoticeDetail templateId={params?.id} type={params?.type} />
            </Drawer>
            <EmailCompanyConfigs
                handleModalSave={handleOk}
                visible={emailVisible}
                handleOnCancel={handleCancel}
                emailInfo={emailInfo || {}}
                disabledList={disabledList}
                defaultOrg={defaultOrg}
                usedEmail={usedEmail}
            />
        </div>
    );
};

export default Form.create()(NoticeTemplate);
